package com.example.bgmachine.bgmachine.commons;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;

import com.example.bgmachine.bgmachine.HttpsUtil;
import com.example.bgmachine.bgmachine.homes.HomePages;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;


public class NetImageView {
    public static final int GET_DATA_SUCCESS = 1;
    public static final int NETWORK_ERROR = 2;
    public static final int SERVER_ERROR = 3;
    public static final int SERVER_TEST= 5;

    public String mfilename = "";
    public String mfilePathname = "";
    public String murlename = "";
    public ImageView mImageView = null;
    Bitmap mbitmaps = null;
    public NetImageView() {

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case GET_DATA_SUCCESS:
                    // Bitmap bitmap = (Bitmap) msg.obj;
                    //setImageBitmap(bitmap);
                    Log.d("aaa", "handleMessage: mfilePathname=1="+mfilePathname);
                    Bitmap bitmap = BitmapFactory.decodeFile(mfilePathname);
                    if (mImageView != null) {
                        mImageView.setImageBitmap(bitmap);
                    }

                    break;
                case NETWORK_ERROR:

                    break;
                case SERVER_ERROR:

                    break;
                case SERVER_TEST:

                    if (mImageView != null) {
                        mImageView.setImageBitmap(mbitmaps);
                    }
                    break;

            }
        }
    };

    public boolean fileIsExists(String fileName) {
        try {
            // 首先保存图片
            File pathsFile = HomePages.mHomePages.getBaseContext().getDir("users", Context.MODE_PRIVATE);//Environment.getExternalStorageDirectory();//getDataDirectory();// mContext.getDir("users", Context.MODE_PRIVATE);

            File appDir = new File(pathsFile, "temp");
            if (!appDir.exists()) {
                Log.d("aaa", "fileIsExists==1");
                appDir.mkdir();
            }else {
                Log.d("aaa", "fileIsExists==2");
            }

            File f = new File(appDir, fileName);
            mfilePathname = f.getAbsolutePath();
            if (f.exists()) {
                Log.i("aaa", "有这个文件="+mfilePathname);
                return true;
            } else {
                Log.i("aaa", "没有这个文件="+mfilePathname);
                return false;
            }
        } catch (Exception e) {
            Log.i("aaa", "崩溃");
            return false;
        }
    }

    public  void saveToSystemGallery(Bitmap bmp) {
        // 首先保存图片
        File pathsFile = HomePages.mHomePages.getBaseContext().getDir("users", Context.MODE_PRIVATE);//Environment.getExternalStorageDirectory();//getDataDirectory();// mContext.getDir("users", Context.MODE_PRIVATE);

        File appDir = new File(pathsFile, "temp");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = mfilename;
        Log.d("aaa", "saveToSystemGallery: mfilePathname=1="+fileName);
        File file = new File(appDir, fileName);

        mfilePathname = file.getAbsolutePath();
        Log.d("aaa", "saveToSystemGallery: mfilePathname=1="+mfilePathname);
        try {
            Log.d("aaa", "saveToSystemGallery=0");
            FileOutputStream fos = new FileOutputStream(file);
            Log.d("aaa", "saveToSystemGallery=01");
            if(mfilePathname.contains(".png")){
                Log.d("aaa", "saveToSystemGallery=02");
                bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
                Log.d("aaa", "saveToSystemGallery=03");
            }
            Log.d("aaa", "saveToSystemGallery=1");
            if(mfilePathname.contains(".jp")){
                Log.d("aaa", "saveToSystemGallery=04");
                bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                Log.d("aaa", "saveToSystemGallery=05");
            }
            Log.d("aaa", "saveToSystemGallery=2");
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Log.d("aaa", "saveToSystemGallery=3");
    }
    public String getFileName(String pathandname){

        int start=pathandname.lastIndexOf("/");
        int end=pathandname.lastIndexOf(".");
        if(start!=-1 && end!=-1){
           // return pathandname.substring(start+1,end);
            int lena = pathandname.length();
            String pthsa = pathandname.substring(start+1,end);
            String pthsb = pathandname.substring(end,lena);
            String pthsc= pthsa+pthsb;
            return pthsc;
        }else{
            return null;
        }

    }
    public boolean isImageFileExist(final String path){
        String tmppath=path;
        tmppath = tmppath.replace("\\","/");
        String filename = getFileName(tmppath);
        return fileIsExists(filename);
    }
    public String getImageFilePaths(final String path){
        String tmppath=path;
        tmppath = tmppath.replace("\\","/");
        String filename = getFileName(tmppath);
        fileIsExists(filename);
        return mfilePathname;
    }
    public void downImageFilePaths(final String path){
        String tmppath=path;
        tmppath = tmppath.replace("\\","/");
        murlename = tmppath;

        new Thread() {
            @Override
            public void run() {
                try {

                    Log.d("aaa", "run==1 ");
                    //把传过来的路径转成URL
                    URL url = new URL(murlename);
                    Log.d("aaa", "run==2 ");
                    //获取连接
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    Log.d("aaa", "run==3 ");
                    //使用GET方法访问网络
                    connection.setRequestMethod("GET");
                    if (connection instanceof HttpsURLConnection) {
                        try {
                            SSLContext sslContext = HttpsUtil.getSSLContextWithCer();
                            Log.d("aaa", "run==4 ");
                            if (sslContext != null) {
                                SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
                                ((HttpsURLConnection) connection).setDefaultSSLSocketFactory(sslSocketFactory);

                            }
                            Log.d("aaa", "run==5 ");
                        } catch (Exception e) {
                            e.printStackTrace();

                        }

                    }
                    Log.d("aaa", "run==6 ");
                    //超时时间为10秒
                    connection.setConnectTimeout(10000);
                    Log.d("aaa", "run==7 ");
                    //获取返回码
                    int code = connection.getResponseCode();
                    Log.d("aaa", "run==8 ");
                    if (code == 200) {
                        InputStream inputStream = connection.getInputStream();
                        //使用工厂把网络的输入流生产Bitmap
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        Log.d("aaa", "run==9 ");

                        inputStream.close();
                        Log.d("aaa", "run==10 ");
                        //saveToSystemGallery(bitmap);

                    } else {
                        //服务启发生错误

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    //网络连接错误

                }
            }
        }.start();
    }
    //设置网络图片
    public void setImageURL(final String path) {
        String tmppath=path;
        tmppath = tmppath.replace("\\","/");
        murlename = tmppath;
        String filename = getFileName(tmppath);
        mfilename = filename;
        Log.d("aaa", "setImageURL: tmppath="+tmppath);
        Log.d("aaa", "setImageURL: mfilename="+mfilename);
        Log.d("aaa", "setImageURL: filename="+filename);
        Log.d("aaa", "setImageURL: murlename="+murlename);
        if (fileIsExists(filename)) {
            Log.d("aaa", "setImageURL: filename=1="+filename);
            Log.d("aaa", "setImageURL: mfilePathname=1="+mfilePathname);
            //利用Message把图片发给Handler
            Message msg = Message.obtain();
            // msg.obj = bitmap;
            msg.obj = "";
            msg.what = GET_DATA_SUCCESS;
            handler.sendMessage(msg);
            return;
        }
        Log.d("aaa", "setImageURL: mfilePathname=2="+mfilePathname);
        //开启一个线程用于联网
        new Thread() {
            @Override
            public void run() {
                try {

                    Log.d("aaa", "run==1 ");
                    //把传过来的路径转成URL
                    URL url = new URL(murlename);
                    Log.d("aaa", "run==2 ");
                    //获取连接
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    Log.d("aaa", "run==3 ");
                    //使用GET方法访问网络
                    connection.setRequestMethod("GET");
                    if (connection instanceof HttpsURLConnection) {
                        try {
                            SSLContext sslContext = HttpsUtil.getSSLContextWithCer();
                            Log.d("aaa", "run==4 ");
                            if (sslContext != null) {
                                SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
                                ((HttpsURLConnection) connection).setDefaultSSLSocketFactory(sslSocketFactory);

                            }
                            Log.d("aaa", "run==5 ");
                        } catch (Exception e) {
                            e.printStackTrace();

                        }

                    }
                    Log.d("aaa", "run==6 ");
                    //超时时间为10秒
                    connection.setConnectTimeout(10000);
                    Log.d("aaa", "run==7 ");
                    //获取返回码
                    int code = connection.getResponseCode();
                    Log.d("aaa", "run==8 ");
                    if (code == 200) {
                        InputStream inputStream = connection.getInputStream();
                        //使用工厂把网络的输入流生产Bitmap
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        Log.d("aaa", "run==9 ");

                        inputStream.close();
                        Log.d("aaa", "run==10 ");
                        saveToSystemGallery(bitmap);
                        mbitmaps = bitmap;
                        //利用Message把图片发给Handler
                        Message msg = Message.obtain();
                        // msg.obj = bitmap;
                        msg.obj = "";
                        msg.what = SERVER_TEST ;//GET_DATA_SUCCESS;
                        handler.sendMessage(msg);
                    } else {
                        //服务启发生错误
                        handler.sendEmptyMessage(SERVER_ERROR);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    //网络连接错误
                    handler.sendEmptyMessage(NETWORK_ERROR);
                }
            }
        }.start();
    }


}
